import { defineStore } from "pinia";

export const useShopStore = defineStore("shopStore", {
  //   state: () => {
  //     return {
  //       count: 0,
  //       cartList: [],
  //       wishlist: [],
  //     };
  //   },
  state: () => ({
    cartList: [],
    wishlist: [],
  }),
  getters: {
    cartCount: (state) => {
      var count = 0;
      for (var i = 0, j = state.cartList.length; i < j; i++) {
        count += state.cartList[i].quantity;
      }
      return count;
    },
    wishlistCount: (state) => {
      var count = 0;
      for (var i = 0, j = state.wishlist.length; i < j; i++) {
        count += state.wishlist[i].quantity;
      }
      return count;
    },
  },
  actions: {
    // 添加到购物车
    addCart(product) {
      //购物车已经存在相同类型
      var hasExistProduct = this.cartList.find((item) => item.id == product.id);
      if (hasExistProduct) {
        hasExistProduct.quantity += product.quantity;
      } else {
        this.cartList.push(product);
      }
    },

    // 添加到心愿单
    addWish(product) {
      var hasExistProduct = this.wishlist.find((item) => item.id == product.id);
      if (hasExistProduct) {
        hasExistProduct.quantity += product.quantity;
      } else {
        this.wishlist.push(product);
      }
    },

    //删除购物车商品
    deleteCartListProduct(id) {
      this.cartList.splice(
        this.cartList.findIndex((item) => item.id === id),
        1
      );
    },
  },
});
